package com.colorfruit.framework.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 *  httpclient连接池扫描无效的连接
 * @author  Odz
 *
 */
public class HttpPoolCleanThread extends Thread {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    private final HttpClientConnectionManager connMgr;
    private volatile boolean shutdown;

    public HttpPoolCleanThread(HttpClientConnectionManager connMgr) {
        super();
        this.connMgr = connMgr;
        logger.warn("{HttpPoolCleanThread} started");
    }


    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(20000);
                    // 关闭无效连接
                    connMgr.closeExpiredConnections();
                    // 可选, 关闭空闲超过60秒的
                    connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
                }
            }
        } catch (InterruptedException ex) {
            logger.error(String.format("closeExpiredConnections error : %s", ex.getMessage()), ex);
        }
    }

    /**
     * 关闭线程
     */
    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
            logger.warn("{HttpPoolCleanThread} stoped");
        }
    }

}
